//
//  CellPictureBrowserView.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/5/16.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
import SDWebImage

/// 选中图片是发出的通知
let FDPostNotifaByPIctureSelected = "FDPostNotifaByPIctureSelected"
///选中图片的索引
let FDPictureSelectedIndex = "FDPictureSelectedIndex"
/// 被选中图片的NSUrl
let FDPictureSelectedNSURL = "FDPictureSelectedNSURL"

class CellPictureBrowserView: UICollectionView {
    
    var status: Status? {
        didSet{
            reloadData()
        }
    }
    /// 懒加载layout
    private var layoutt : UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    
     init()
     {
        super.init(frame: CGRectZero, collectionViewLayout: layoutt)
        
        // 行间距
        layoutt.minimumLineSpacing = padding
        layoutt.scrollDirection = UICollectionViewScrollDirection.Vertical
        
        // item间距
        dataSource = self
        delegate = self
        layoutt.minimumInteritemSpacing = padding
        backgroundColor = UIColor.whiteColor()
        registerClass(StatusCollectCell.self, forCellWithReuseIdentifier: "yyy")

     }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    
    //MARK: - 计算插图的大小和 item的size
     func calculateImageSize() ->(viewSize: CGSize, itmeSize: CGSize) {
        
        // 配图个数
        let count = status?.withMap_urls?.count
        
        if count == 0 || count == nil {
            return (CGSizeZero, CGSizeZero)
        }
        if count == 1 {
            // 取出缓存的图片
            let key = status?.withMap_urls?.first?.absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key!)
            let imgSize = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale)
            layoutt.itemSize = imgSize

            return (imgSize, imgSize)
        }
        
        let itemWidth = 90
        let spacing = Int(padding)
        
        if count == 4 {
            let viewWidth =  itemWidth * 2 + spacing
            layoutt.itemSize = CGSize(width: itemWidth, height: itemWidth)

            return (CGSize(width: viewWidth, height: viewWidth), CGSize(width: itemWidth, height: itemWidth))
        }
        
        // 2 3 6 7 8 9 张照片
        
        let lie = 3
        let hang = (count! - 1) / lie + 1
        let viewWidth = lie * itemWidth + (lie - 1) * spacing
        let viewHeight = hang * itemWidth + (hang - 1) * spacing
        layoutt.itemSize = CGSize(width: itemWidth, height: itemWidth)
        return (CGSize(width: viewWidth, height: viewHeight), CGSize(width: itemWidth, height: itemWidth))
    
}
    
}


/// 自定义cell
class StatusCollectCell: UICollectionViewCell {
    
    var  imgUrl: NSURL?{
        didSet{
            if let url = imgUrl{
                img.sd_setImageWithURL(url)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        img.contentMode = UIViewContentMode.ScaleAspectFill
        img.clipsToBounds = true
        contentView.addSubview(img)
        
        img.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private  lazy var img : UIImageView = UIImageView()
}

    
// MARK: - 数据源协议
extension CellPictureBrowserView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.chaTu_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("yyy", forIndexPath: indexPath) as! StatusCollectCell
        cell.imgUrl = status?.chaTu_urls![indexPath.item]
        return
        cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let imgArrs = status?.chaTu_large_urls
        let info = [FDPictureSelectedIndex: indexPath.item , FDPictureSelectedNSURL: imgArrs!]
        NSNotificationCenter.defaultCenter().postNotificationName(FDPostNotifaByPIctureSelected, object: self, userInfo: info as [NSObject : AnyObject])
    }
}